package cn.itcast.bos.before.utils;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

public class MailUtils {
	private static String SMTP_HOST = "smtp.163.com"; // 网易
	private static String SMTP_ACCOUNT = "maliang_efh@163.com"; // 邮箱账户
	private static String SMTP_PASSWORD = "bjfcm1c"; // 邮箱授权码

	public static void sendMail(String subject, String content, String to) {
		Properties props = new Properties();
		props.setProperty("mail.smtp.host", SMTP_HOST);
		props.setProperty("mail.transport.protocol", "smtp");
		props.setProperty("mail.smtp.auth", "true");
		props.setProperty("mail.debug", "true"); // 开启调试
		 
		Session session = Session.getInstance(props);
		Message message = new MimeMessage(session);
		try {
			message.setFrom(new InternetAddress(SMTP_ACCOUNT));
			message.setRecipient(RecipientType.TO, new InternetAddress(to));
			message.setSubject(subject);
			message.setContent(content, "text/html;charset=utf-8");
			Transport transport = session.getTransport();
			transport.connect(SMTP_HOST, SMTP_ACCOUNT, SMTP_PASSWORD);
			transport.sendMessage(message, message.getAllRecipients());
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("邮件发送失败...");
		}
	}

	public static String mailUrl(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String path = request.getContextPath();
		return path;
	}
	public static void main(String[] args) {
		sendMail("邮箱验证", 
				"您好，点击以下链接验证您的邮箱：", 
				"maliang_efh@163.com");
	}
}
